//
//  THCPCSearchVC.m
//  YJB
//
//  Created by 中电大维 on 2016/12/24.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "THCPCSearchVC.h"
#import "YJVerticalButton.h"
#import "masonry.h"
#import "YJSearchBar.h"
#import "THCpcHallCell.h"
#import "THCpcHallModel.h"
#import "THFlowEarnHallModel.h"
#import "THFlowEarnHallCell.h"
#import "THFlowEarnCurrentTaskDetailVC.h"
#import "THFlowEarnReportVC.h"
#import "THFlowEarnHallModel.h"
#import "THReportView.h"

@interface THCPCSearchVC ()<THReportDelegate>

@property (nonatomic, strong)UIButton *publishBtn;
@property (nonatomic, strong)UIButton *priceBtn;
@property (nonatomic,weak)YJSearchBar *searchBar;
@property (nonatomic,strong)THReportView *reportView;
@property (nonatomic, strong)NSMutableArray *tasks;

@end

@implementation THCPCSearchVC
{
    THFlowEarnReportVC *_controller;
    THFlowEarnHallModel *_model;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNav];
    [self addButton];
    [self.searchBar becomeFirstResponder];
    self.tableView.tableFooterView = [UIView new];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"eeeeee"];
    [self.tableView registerClass:[THFlowEarnHallCell class] forCellReuseIdentifier:flowEarnHallCellID];
    
    UILongPressGestureRecognizer *longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
    longPressGR.minimumPressDuration = 1.0;
    [self.tableView addGestureRecognizer:longPressGR];
    _controller = [[THFlowEarnReportVC alloc] init];
    _model = [[THFlowEarnHallModel alloc] init];
    
}

-(void)longPressToDo:(UILongPressGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateBegan) {
        self.reportView.hidden = NO;
        CGPoint point = [gesture locationInView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
        _model = self.tasks[indexPath.row];
        _controller.reportType = 1;
        _controller.reportTitle = _model.sitename;
        _controller.reportID = _model.ID;
    }
}

- (void)loadData
{
    [self.tasks removeAllObjects];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *userName = [YJUserDefaultTool readUserName];
    NSString *md5Key = [YJUserDefaultTool readKeyID];
    params[@"action"] = @"get_all_cpclist";
    params[@"makegold"] = @{@"username":userName,
                            @"firstrow":@"-1",
                            @"listrows":@"",
                            @"user_info":userName,
                            @"phone_info":@"iOS",
                            @"md5_key":md5Key};
    [YJNetworkTool postWithUrl:THURL(@"clickcpc.php") parameters:params success:^(id responseObject) {
        NSString *code = responseObject[@"return"][@"code"];
        if (code.integerValue == 200)
        {
            NSArray *array = responseObject[@"return"][@"data"][@"list"];
            self.tasks = [THCpcHallModel mj_objectArrayWithKeyValuesArray:array];
        }
        else if(code.integerValue == 500)
            [self.tasks removeAllObjects];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"网络不佳，稍后重试" toView:self.view];
    }];
}
- (void)cancelClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchItemClick
{
    /*
     获取{"action":"get_select_list","makegold":{"username":"用户名","sel_type":"搜索范围（1：标题和发布者名称 2：只搜发布者名称 3：搜索标题）","sel_value":"搜索内容","firstrow":"当前页码（-1：获取全部；>=0：页码）","listrows":"每页数目（不传默认为10）","user_info":"用户信息","phone_info":"手机信息","md5_key":"密钥"}}
     */
    [self.tasks removeAllObjects];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *userName = [YJUserDefaultTool readUserName];
    NSString *md5Key = [YJUserDefaultTool readKeyID];
    NSString *url = THURL(@"manual.php");
    NSString *type = self.publishBtn.selected?@"2":@"1";
    
    params[@"action"] = @"get_select_list";
    params[@"makegold"] = @{@"username":userName,
                            @"sel_type":type,
                            @"sel_value":self.searchBar.text,
                            @"firstrow":@"-1",
                            @"listrows":@"",
                            @"user_info":userName,
                            @"phone_info":@"iOS",
                            @"md5_key":md5Key};
    
    if (self.priceBtn.selected) {
        params[@"action"] = @"get_again_sort";
        params[@"makegold"] = @{@"username":userName,
                                @"type":@"1",
                                @"key":@"2",
                                @"firstrow":@"-1",
                                @"listrows":@"",
                                @"user_info":userName,
                                @"phone_info":@"iOS",
                                @"md5_key":md5Key};
    }

    [YJNetworkTool postWithUrl:url parameters:params success:^(id responseObject) {
        NSString *code = responseObject[@"return"][@"code"];
        if (code.integerValue == 200)
        {
            NSArray *array = responseObject[@"return"][@"data"][@"list"];
            self.tasks = [THFlowEarnHallModel mj_objectArrayWithKeyValuesArray:array]
            ;
        }
        else if(code.integerValue == 500)
            [self.tasks removeAllObjects];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"网络不佳，稍后重试" toView:self.view];
    }];
}

- (void)resultUpdate:(YJSearchBar *)searchBar
{
    [self.tasks removeAllObjects];
    [self.tableView reloadData];
    if (searchBar.text.length)
    {
        [self.publishBtn setHidden:YES];
        [self.priceBtn setHidden:YES];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchItemClick)];
        [self searchItemClick];
    }else
    {
        self.priceBtn.hidden = NO;
        self.publishBtn.hidden = NO;
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClick)];
    }
}
- (void)sort:(UIButton *)button
{
    if (button.tag == 1) {//按发布人
        self.searchBar.placeholder = @"发布人";
        self.publishBtn.hidden = YES;
        self.priceBtn.hidden = YES;
        self.publishBtn.selected = YES;
        self.priceBtn.selected = NO;
        
    }else{//按价格最高
        
        //self.searchBar.placeholder = @"价格最高";
        self.publishBtn.hidden = YES;
        self.priceBtn.hidden = YES;
        self.publishBtn.selected = NO;
        self.priceBtn.selected = YES;
        self.searchBar.text = @"价格最高";
        [self searchItemClick];
    }
}

#pragma mark -------------- tableview Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tasks.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    THFlowEarnHallCell *cell = [tableView dequeueReusableCellWithIdentifier:flowEarnHallCellID forIndexPath:indexPath];
    cell.model = self.tasks[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    THFlowEarnHallModel *model = self.tasks[indexPath.row];
    THFlowEarnCurrentTaskDetailVC *vc = [[THFlowEarnCurrentTaskDetailVC alloc] init];
    vc.title = @"手动赚钱";
    vc.url = model.url;
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    THFlowEarnHallModel *model = self.tasks[indexPath.row];
    return model.cellHeight;
}


- (void)pushReportController
{
    [self.navigationController pushViewController:_controller animated:YES];
}

- (YJSearchBar *)searchBar
{
    if (_searchBar == nil)
    {
        YJSearchBar *search = [YJSearchBar searchBar];
        search.placeholder = @"用户名/任务标题";
        search.frame = CGRectMake(0, 0, 26 * GRIDW, 35);
        search.font = [UIFont systemFontOfSize:16.0f];
        [search addTarget:self action:@selector(resultUpdate:) forControlEvents:UIControlEventEditingChanged];
        search.clearButtonMode = UITextFieldViewModeAlways;
        search.background = nil;
        self.navigationItem.titleView = search;
        search.backgroundColor = [UIColor whiteColor];
        [search.layer setMasksToBounds:YES];
        [search.layer setCornerRadius:5.0];
        _searchBar = search;
    }
    return _searchBar;
}

- (void)setupNav
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClick)];
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}


- (void)addButton
{
    NSArray *titles = [[NSArray alloc] initWithObjects:@"发布人",@"价格最高", nil];
    NSArray *images = [[NSArray alloc] initWithObjects:@"th_cpc_publiser",@"th_cpc_price", nil];
    NSMutableArray *buttons = [[NSMutableArray alloc] init];
    for (int i = 0; i < 2; i ++)
    {
        float width = self.view.width*0.25;
        float height = width+25;
        float x = (self.view.width-width*2)/3.0+i*(width+(self.view.width-width*2)/3.0);
        float y = 55;
        CGRect frame = CGRectMake(x, y, width, height);
        UIButton *button = [[UIButton alloc]initWithFrame:frame];
        button.tag = i + 10;
        [button setTitle:titles[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor]  forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15.0f];
        [button setImage:Image(images[i]) forState:UIControlStateNormal];
        // 按钮图片和标题总高度
        CGFloat totalHeight = (button.imageView.frame.size.height + button.titleLabel.frame.size.height);
        // 设置按钮图片偏移
        [button setImageEdgeInsets:UIEdgeInsetsMake(-(totalHeight - button.imageView.frame.size.height), 0.0, 0.0, -button.titleLabel.frame.size.width)];
        // 设置按钮标题偏移
        [button setTitleEdgeInsets:UIEdgeInsetsMake(0.0, -button.imageView.frame.size.width, -(totalHeight - button.titleLabel.frame.size.height),0.0)];
        button.tag = i+1;
        [button addTarget:self action:@selector(sort:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        [buttons addObject:button];
        
        if (i) {
            self.priceBtn = button;
            self.priceBtn.x -= 7.5;
        }else{
            self.publishBtn = button;
            self.publishBtn.x += 7.5;
        }
    }
}

- (NSMutableArray *)tasks
{
    if (!_tasks) {
        _tasks = [[NSMutableArray alloc] init];
    }
    return _tasks;
}

- (THReportView *)reportView
{
    if (!_reportView) {
        _reportView = [[THReportView alloc] init];
        _reportView.titlename = @"举报";
        _reportView.hidden = YES;
        _reportView.delegate = self;
        [[UIApplication sharedApplication].keyWindow addSubview:_reportView];
    }
    return _reportView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
